<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Search extends SB_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->model('search_model');
		$this->index($this->uri->segment(2));
	}
	
	function index($sText = '')
	{
		$sText = htmlEscape(strtolower(urldecode($sText)));

		preg_match_all('/[\wа-я]{3,}/iu', $sText, $sVal);
		$content = '';

		if (!is_arr($sVal = $sVal[0]))
		{
			$content = 'Как-то несерьезно...';
		}
		else
		{
			$data = array(
				'title' => 'Результаты поиска: '.$sText,
				'entry' => $this->search_model->blogs($sVal)
			);

			if (is_arr($data['entry']))
			{
				$data['blogs'] = $this->main_model->getBlogs(extractFieldFromDataArray($data['entry'], 'tBlog'));
				$data['users'] = $this->user->getUsernamesByIds(extractFieldFromDataArray($data['entry'], 'tUserCreated'));
				$cats = $this->main_model->getArticleCategoriesWithGroup(extractFieldFromDataArray($data['entry'], 'id'));
				$catsIds = array();
				foreach ($data['entry'] as &$val) {
					if (isset($cats[$val->id])) {
						$val->tCategory = $cats[$val->id];
						$catsIds = array_merge($catsIds, $cats[$val->id]);
					} else {
						$val->tCategory = array();
					}
				}
				$catsIds = array_unique($catsIds);
				$data['categories'] = $this->main_model->getCategoriesById($catsIds);
				
				$content = $this->load->view('content_list', $data, true);
			}
			else
				$content = 'Ничего не найдено';
		}

		$this->getPage(array(
			'content' => $content,
			'title' => 'Поиск',
			'searchText' => $sText
		));
	}


}
?>